package com.hikvision.open.app.ui.local

import android.graphics.SurfaceTexture
import android.os.Bundle
import android.view.TextureView
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.hikvision.hatomplayer.PlayCallback
import com.hikvision.open.app.utils.inflate
import hik.sdk.demo.databinding.ActivityLocalPlayBinding
import java.text.DecimalFormat

/**
 * <p> 本地录像播放界面 </p>
 * @author 段自航 2021/7/27 10:09
 * @version V1.0
 */
class LocalVideoPlayActivity : AppCompatActivity(), TextureView.SurfaceTextureListener {

    companion object {
        const val MEDIA_FILE_PATH = "mediaFilePath"
    }

    /*录像文件路径*/
    private val filePath by lazy {
        intent.extras?.get(MEDIA_FILE_PATH) as String ?: ""
    }

    private val format = DecimalFormat("00")

    private val viewBinding: ActivityLocalPlayBinding by inflate()

    private val viewModel by viewModels<LocalPlayViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initView()
        initViewModel()
    }

    private fun initView() {
        viewBinding.backImage.setOnClickListener { finish() }
        viewBinding.textureView.surfaceTextureListener = this
        viewBinding.startImage.setOnClickListener {
            viewBinding.startImage.isVisible = false
            viewModel.startPlay(filePath, viewBinding.textureView.surfaceTexture!!)
        }
        viewBinding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                viewModel.progress = progress
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                viewModel.isSeekBarTouch = true
                cancelUpdateTime()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                viewModel.isSeekBarTouch = false
                val progress = seekBar.progress
                viewModel.progress = progress
                viewModel.playByProgress(progress.toDouble())
            }
        })
        viewBinding.captureButton.setOnClickListener {
            viewModel.capture()
            Toast.makeText(this, "抓拍成功", Toast.LENGTH_SHORT).show()
        }
        viewBinding.pauseButton.setOnClickListener {
            executePause()
        }
        viewBinding.soundButton.setOnClickListener {
            executeSound()
        }
    }

    private fun initViewModel() {
        viewModel.playProgressResult.observe(this, Observer {
            startUpdateTime()
        })
        viewModel.playResult.observe(this, Observer {
            when (it.status) {
                PlayCallback.Status.SUCCESS -> {
                    //播放成功，设置视频总时间
                    viewBinding.seekBar.progress = 0
                    val totalTime = viewModel.getTotalTime()
                    viewModel.fileTotalTime = if (totalTime <= 0L) { //获取总时长返回-1或0，需要处理，避免崩溃
                        1
                    } else {
                        totalTime
                    }
                    viewBinding.rightTimeText.text = getTimeText(totalTime)
                    enableControlView(true)
                    //播放成功后，就要开始不断获取OSD时间
                    startUpdateTime()
                }
                PlayCallback.Status.FINISH -> {
                    //当播放器关闭时也要定时器给关闭
                    cancelUpdateTime()
                    viewBinding.startImage.isVisible = true
                    viewBinding.leftTimeText.text = "00:00"
                    enableControlView(false)
                }
                else -> {

                }
            }
        })
    }

    private fun enableControlView(enable: Boolean) {
        viewBinding.pauseButton.isEnabled = enable
        viewBinding.captureButton.isEnabled = enable
        viewBinding.soundButton.isEnabled = enable
        if (!enable) {
            viewBinding.soundButton.isSelected = enable
        }
    }

    /**
     * 开始刷新回放时间
     */
    private fun startUpdateTime() {
        viewBinding.root.postDelayed(osdTask, 400)
    }

    /**
     * 停止刷新回放时间
     */
    private fun cancelUpdateTime() {
        viewBinding.root.removeCallbacks(osdTask)
    }

    /**
     * 每隔100ms获取一次当前的系统时间的任务
     */
    private val osdTask = Runnable {
        val osdTime = viewModel.getPlayTime()
        if (osdTime > -1 && !viewModel.isSeekBarTouch) {
            //post的时候一定不能使用new Runnable,这会导致创建很多任务，消耗内存
            viewBinding.seekBar.progress = (osdTime * 100.0f / viewModel.fileTotalTime).toInt()
            viewBinding.leftTimeText.text = getTimeText(osdTime)
        }
        startUpdateTime()
    }

    private fun getTimeText(seconds: Long): String {
        if (seconds <= 0L) return "00:00"
        val minute = seconds / 60
        val leftSeconds = seconds % 60
        val minuteText = format.format(minute)
        val secondsText = format.format(leftSeconds)
        return "$minuteText:$secondsText"
    }

    private fun executeSound() {
        if (!viewModel.isSound) {
            if (viewModel.openAudio(true)) {
                viewBinding.soundButton.isSelected = true
            }
        } else {
            if (viewModel.openAudio(false)) {
                viewBinding.soundButton.isSelected = false
            }
        }
    }

    private fun executePause() {
        if (!viewModel.isPause) {
            if (viewModel.pause()) {
                //暂停时要将定时器也停止
                cancelUpdateTime()
                viewBinding.pauseButton.isSelected = true
                viewBinding.pauseButton.text = "播放"
                viewBinding.soundButton.isEnabled = false
            }
        } else {
            if (viewModel.resume()) {
                //暂停时要将定时器也恢复
                startUpdateTime()
                viewBinding.pauseButton.isSelected = false
                viewBinding.pauseButton.text = "暂停"
                viewBinding.soundButton.isEnabled = true
            }
        }
    }


    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        return false
    }
}